const { ccclass, menu, requireComponent } = cc._decorator


/**
 * @description 基于多边形数据的不规则按钮
 * @author mirahs
 * @email 2892727493@qq.com
 */
@ccclass
@requireComponent(cc.PolygonCollider)
@menu("UI/PolygonButtonComp")
export default class PolygonButtonComp extends cc.Component {
    private cb: Function

    private _isTouchStart: boolean = false
    private _isBig: boolean = false


    protected onLoad(): void {
        this.node.on(cc.Node.EventType.TOUCH_START, (et: cc.Event.EventTouch) => this.onTouchStart(et))
        this.node.on(cc.Node.EventType.TOUCH_MOVE, (et: cc.Event.EventTouch) => this.onTouchMove(et))
        this.node.on(cc.Node.EventType.TOUCH_END, (et: cc.Event.EventTouch) => this.onTouchEnd(et))
        this.node.on(cc.Node.EventType.TOUCH_CANCEL, (_et: cc.Event.EventTouch) => this.onTouchCancel())
    }


    public setClickCallback(cb: Function) {
        this.cb = cb
    }


    private onTouchStart(et: cc.Event.EventTouch) {
        if (!this.checkClick(et.getLocation())) return

        this._isTouchStart = true

        this._isBig = true
        cc.tween(this.node).to(0.1, { scale: 1.1 }).start()
    }

    private onTouchMove(et: cc.Event.EventTouch) {
        if (!this._isTouchStart) return

        const isClick = this.checkClick(et.getLocation())

        if (isClick && !this._isBig) {
            this._isBig = true
            cc.tween(this.node).to(0.1, { scale: 1.1 }).start()
        } else if (!isClick && this._isBig) {
            this._isBig = false
            cc.tween(this.node).to(0.1, { scale: 1 }).start()
        }
    }

    private onTouchEnd(et: cc.Event.EventTouch) {
        if (!this._isTouchStart) return
        this._isTouchStart = false

        const isClick = this.checkClick(et.getLocation())

        if (!isClick && !this._isBig) return

        isClick && this.cb && this.cb(this.node)

        if (this._isBig) {
            this._isBig = false
            cc.tween(this.node).to(0.1, { scale: 1 }).start()
        }
    }

    private onTouchCancel() {
        if (!this._isTouchStart) return
        this._isTouchStart = false

        if (!this._isBig) return
        this._isBig = false

        cc.tween(this.node).to(0.1, { scale: 1 }).start()
    }


    private checkClick(worldPos: cc.Vec2): boolean {
        const nodePos = this.node.convertToNodeSpaceAR(worldPos)
        const points = this.node.getComponent(cc.PolygonCollider).points

        return cc.Intersection.pointInPolygon(nodePos, points)
    }
}
